import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import type { CartItem, CartSummary, CartItemAddRequest, Stock } from '@/types'
import { cartService } from '@/api'
import { useAuthStore } from './auth'
import { createLogger } from '@/utils/logger'
import { useAuthModalStore } from './authModal'

const cartLogger = createLogger('Cart')

export const useCartStore = defineStore('cart', () => {
  // State
  const items = ref<CartItem[]>([])
  const summary = ref<CartSummary>({
    totalItems: 0,
    totalPrice: 0,
    selectedItems: 0,
    selectedPrice: 0,
  })
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // Getters
  const totalItems = computed(() => summary.value.totalItems)
  const totalPrice = computed(() => summary.value.totalPrice)
  const selectedItems = computed(() => summary.value.selectedItems)
  const selectedPrice = computed(() => summary.value.selectedPrice)
  const isEmpty = computed(() => items.value.length === 0)
  const selectedItemsList = computed(() => items.value.filter((item) => item.selected))

  // Actions
  // 内部使用
  const setItems = (cartItems: CartItem[]) => {
    items.value = cartItems
  }

  // 内部使用
  const setSummary = (cartSummary: CartSummary) => {
    summary.value = cartSummary
  }

  // 内部使用
  const addError = (message: string) => {
    error.value = message
  }

  const clearError = () => {
    error.value = null
  }

  const loadCart = async () => {
    const authStore = useAuthStore()

    if (!authStore.isAuthenticated) {
      // 未登录时从本地存储加载
      const localCart = JSON.parse(localStorage.getItem('localCart') || '[]')
      items.value = localCart
      updateSummary()
      return
    }

    isLoading.value = true
    error.value = null

    try {
      const [cartResponse, summaryResponse] = await Promise.all([
        cartService.getCartItems(),
        cartService.getCartSummary(),
      ])

      items.value = cartResponse.data.data
      summary.value = summaryResponse.data.data

      // 同步到本地存储
      localStorage.setItem('cart', JSON.stringify(items.value))
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : '加载购物车失败'
      error.value = message
      console.error('Load cart error:', err)
    } finally {
      isLoading.value = false
    }
  }

  const addToCart = async (skuId: number, quantity: number = 1) => {
    const authStore = useAuthStore()

    if (!authStore.isAuthenticated) {
      const modal = useAuthModalStore()
      modal.openLogin('/cart', '登录后即可将商品加入购物车')
      return { success: false, error: '请先登录', needLogin: true }
    }

    isLoading.value = true
    error.value = null

    try {
      // 构建请求参数
      const addRequest = {
        skuId: skuId, // 使用传入的skuId
        quantity,
      }

      const response = await cartService.addToCart(addRequest)
      await loadCart()
      return { success: true, data: response.data.data }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : '添加商品到购物车失败'
      error.value = message
      return { success: false, error: message }
    } finally {
      isLoading.value = false
    }
  }

  const updateQuantity = async (cartItemId: number, quantity: number) => {
    if (quantity <= 0) {
      return removeFromCart(cartItemId)
    }

    const authStore = useAuthStore()

    if (!authStore.isAuthenticated) {
      // 未登录时更新本地购物车
      const localCart: Array<CartItem & { cartItemId: number }> = JSON.parse(
        localStorage.getItem('localCart') || '[]',
      )
      const item = localCart.find((item) => item.cartItemId === cartItemId)
      if (item) {
        item.quantity = quantity
        localStorage.setItem('localCart', JSON.stringify(localCart))
        items.value = localCart
        updateSummary()
      }
      return { success: true }
    }

    isLoading.value = true
    error.value = null

    try {
      await cartService.updateCartItem({
        cartId: cartItemId, // 后端使用cartId参数
        quantity,
      })
      await loadCart()
      return { success: true }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : '更新商品数量失败'
      error.value = message
      return { success: false, error: error.value }
    } finally {
      isLoading.value = false
    }
  }

  const removeFromCart = async (cartItemId: number) => {
    const authStore = useAuthStore()

    if (!authStore.isAuthenticated) {
      const localCart: Array<CartItem & { cartItemId: number }> = JSON.parse(
        localStorage.getItem('localCart') || '[]',
      )
      const filteredCart = localCart.filter((item) => item.cartItemId !== cartItemId)
      localStorage.setItem('localCart', JSON.stringify(filteredCart))
      items.value = filteredCart
      updateSummary()
      return { success: true }
    }

    isLoading.value = true
    error.value = null

    try {
      await cartService.removeFromCart(cartItemId)
      await loadCart()
      return { success: true }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : '删除商品失败'
      error.value = message
      return { success: false, error: message }
    } finally {
      isLoading.value = false
    }
  }

  const selectItem = async (cartItemId: number, selected: boolean) => {
    const authStore = useAuthStore()

    if (!authStore.isAuthenticated) {
      const localCart: Array<CartItem & { cartItemId: number }> = JSON.parse(
        localStorage.getItem('localCart') || '[]',
      )
      const item = localCart.find((item) => item.cartItemId === cartItemId)
      if (item) {
        item.selected = selected
        localStorage.setItem('localCart', JSON.stringify(localCart))
        items.value = localCart
        updateSummary()
      }
      return { success: true }
    }

    try {
      await cartService.selectCartItem(cartItemId, selected)
      await loadCart()
      return { success: true }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : '选择商品失败'
      error.value = message
      return { success: false, error: message }
    }
  }

  const selectAll = async (selected: boolean) => {
    const authStore = useAuthStore()

    if (!authStore.isAuthenticated) {
      const localCart: Array<CartItem & { selected?: boolean }> = JSON.parse(
        localStorage.getItem('localCart') || '[]',
      )
      localCart.forEach((item) => (item.selected = selected))
      localStorage.setItem('localCart', JSON.stringify(localCart))
      items.value = localCart
      updateSummary()
      return { success: true }
    }

    try {
      await cartService.selectAllCartItems(selected)
      await loadCart()
      return { success: true }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : '全选商品失败'
      error.value = message
      return { success: false, error: message }
    }
  }

  const clearCart = async () => {
    const authStore = useAuthStore()

    if (!authStore.isAuthenticated) {
      localStorage.removeItem('localCart')
      items.value = []
      updateSummary()
      return { success: true }
    }

    isLoading.value = true
    error.value = null

    try {
      await cartService.clearCart()
      await loadCart()
      return { success: true }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : '清空购物车失败'
      error.value = message
      return { success: false, error: message }
    } finally {
      isLoading.value = false
    }
  }

  const updateSummary = () => {
    const selectedItemsList = items.value.filter((item) => item.selected)

    summary.value = {
      totalItems: items.value.reduce((sum, item) => sum + item.quantity, 0),
      totalPrice: items.value.reduce((sum, item) => {
        const stock = typeof item.stock === 'number' ? undefined : item.stock
        const price = stock?.discountPrice ?? stock?.price ?? item.price ?? 0
        return sum + price * item.quantity
      }, 0),
      selectedItems: selectedItemsList.reduce((sum, item) => sum + item.quantity, 0),
      selectedPrice: selectedItemsList.reduce((sum, item) => {
        const stock = typeof item.stock === 'number' ? undefined : item.stock
        const price = stock?.discountPrice ?? stock?.price ?? item.price ?? 0
        return sum + price * item.quantity
      }, 0),
    }
  }

  const getSelectedItems = () => items.value.filter((item) => item.selected)

  const getItemCount = () => items.value.reduce((sum, item) => sum + item.quantity, 0)

  // 监听认证状态变化
  const init = () => {
    const authStore = useAuthStore()

    // 监听登录状态变化
    authStore.$subscribe((mutation, state) => {
      if (state.isAuthenticated) {
        loadCart()
      } else {
        // 登出时清空购物车
        items.value = []
        summary.value = {
          totalItems: 0,
          totalPrice: 0,
          selectedItems: 0,
          selectedPrice: 0,
        }
      }
    })

    // 初始加载
    loadCart()
  }

  init()

  return {
    // State
    items: readonly(items),
    summary: readonly(summary),
    isLoading: readonly(isLoading),
    error: readonly(error),

    // Getters
    totalItems,
    totalPrice,
    selectedItems,
    selectedPrice,
    isEmpty,
    selectedItemsList,

    // Actions
    loadCart,
    addToCart,
    updateQuantity,
    removeFromCart,
    selectItem,
    selectAll,
    clearCart,
    getSelectedItems,
    getItemCount,
    clearError,
  }
})
